package threads;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ParallelMax {

	public static void main(String[] args) {
	  int[] list= new int[5000000];
	  for(int i=0;i<list.length;i++) {
		  list[i]=i;
	  }
	  long start1=System.currentTimeMillis();
	  System.out.println("The max of the list is: "+max(list));
	  long end1=System.currentTimeMillis();
	  System.out.println("The Parallel method take of "+(end1-start1));
	  
	  
	  
//	  long start2=System.currentTimeMillis();
//	  System.out.println("The max of the list is: "+max1(list));
//	  long end2=System.currentTimeMillis();
//	  System.out.println("The Ordinary method take of "+(end2-start2));
	  

	}
	
	public static Integer max(int[] list) {
		
		RecursiveTask<Integer> task=new MaxTask(list,0,list.length);
		ForkJoinPool pool=new ForkJoinPool();
		return pool.invoke(task);
		
		
		
	}
	
	public static Integer max1(int [] list) {
		int max=list[0];
		for(int i=0;i<list.length;i++) {
			if(list[i]>max)
				max=list[i];
		}
		return new Integer(max);
	}
	
	
	private static class MaxTask extends RecursiveTask<Integer>{
		
		
		int[] list;
		int low;
		int height;
		
		public MaxTask(int[] list,int low,int height) {
			this.list=list;
			this.low=low;
			this.height=height;
		}

		@Override
		protected Integer compute() {
			
			if(height-low<1000) {
				int max=list[0];
				for(int i=0;i<list.length;i++) {
					if(list[i]>max)
						max=list[i];
				}
				return new Integer(max);
			}
			else {
				int mid=(low+height)/2;
				RecursiveTask<Integer> left=new MaxTask(list,low,mid);
				RecursiveTask<Integer> right=new MaxTask(list,mid,height);
				left.fork();
				right.fork();
				return new Integer(Math.max(left.join().intValue(),right.join().intValue()));
			}
			
			
			
			
			// TODO 自动生成的方法存根
			
		}
		
	}

}




